package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class SmsUtil {

    @Autowired
    private SmsProperties prop;

    @Autowired
    private IAcsClient client;

    public void sendVerifyCode(String phone, String code) {
        String param = String.format("{\"code\":\"%s\"}", code);
        this.sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(), param);
    }

    private void sendMessage(String phone, String signName, String template, String param) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(prop.getDomain());
        request.setVersion(prop.getVersion());
        request.setAction(prop.getAction());
        request.putQueryParameter("RegionId", prop.getRegionID());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", template);
        request.putQueryParameter("TemplateParam", param);
        try {
            CommonResponse response = client.getCommonResponse(request);
            Map<String, String> data = JsonUtils.toMap(response.getData(), String.class, String.class);
            if (!"OK".equalsIgnoreCase(data.get("Code"))) {
                throw new RuntimeException(data.get("Message"));
            }
            log.info("发送短信成功，手机号：{}", phone);
        } catch (Exception e) {
            log.error("发送短信失败，原因：{}", e.getMessage(), e);
        }
    }
}
